package com.atguigu.ucenterservice.controller;

import com.atguigu.servicebase.exceptionhandler.GuiliException;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utils.ConstantWxUtils;
import com.atguigu.ucenterservice.utils.HttpClientUtils;
import com.google.gson.Gson;
import common.atguigu.commonutils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller//只请求地址，不返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UcenterMemberService memberService;


    //2获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(String code,String state)  {
        try {
            System.out.println("code"+code);
            System.out.println("state"+state);
            //根据code请求，微信固定的地址，得到access_token，openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数，code，id，密钥
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //请求这个拼接好的地址，得到两个值，access_token，openid
            //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //从accessTokenInfo取出access_token，openid,
            //accessTokenInfo里数据是字符串结构，把accessTokenInfo转换程Map集合，用gson工具
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");



            //扫码人信息添加到数据库
            //先根据openid判断数据库里有没有这条微信数据
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member==null){

                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid);
                //使用httpclient发送请求，得到返回结果
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取扫码人信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");//昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//头像

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            //使用jwt生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //最后返回首页
            return "redirect:http://localhost:3000?token"+jwtToken;

        }catch (Exception e){
            throw new GuiliException(20001,"登录失败！");
        }
    }


    //1生成扫描微信二维码
    @GetMapping("login")
    public String genQrConnect(HttpSession session){
        // 微信开放平台授权baseUrl,%s相当于？占位符，可以向该字符串中传参数
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //将字符串 url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuiliException(20001, e.getMessage());

        }
        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "state"
        );

        return "redirect:" + qrcodeUrl;
    }
}
